import SparkMD5 from 'spark-md5'

/**
 * @description: 分块计算文件的md5值
 * @param {*} file 文件
 * @param {*} chunkSize 分片大小
 * @returns {*}
 */
function calculateFileMd5(file, chunkSize, chunkFiles = []) {
    return new Promise((resolve, reject) => {
        const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
        const chunks = Math.ceil(file.size / chunkSize)
        let currentChunk = 0
        const spark = new SparkMD5.ArrayBuffer()
        const fileReader = new FileReader()

        fileReader.onload = function (e) {
            spark.append(e.target.result)
            currentChunk++
            if (currentChunk < chunks) {
                loadNext()
            } else {
                const md5 = spark.end()
                resolve(md5)
            }
        }

        fileReader.onerror = function (e) {
            reject(e)
        }

        function loadNext() {
            const start = currentChunk * chunkSize
            let end = start + chunkSize
            if (end > file.size) {
                end = file.size
            }
            let chunk = blobSlice.call(file, start, end);
            chunkFiles.push(chunk);
            fileReader.readAsArrayBuffer(chunk);
        }

        loadNext()
    })
}

/**
 * @description: 分块计算文件的md5值
 * @param {*} file 文件
 * @returns {Promise}
 */
function calculateFileMd5ByDefaultChunkSize(file, chunkSize = 1024 * 1024 * 1, chunkFiles = []) {
    return calculateFileMd5(file, chunkSize, chunkFiles)
}

/**
 * @description: 文件切片
 * @param {*} file
 * @param {*} size 切片大小
 * @returns [{file}]
 */
function createFileChunk(file, size = 1024 * 1024 * 1) {
    const chunks = []
    let cur = 0
    while (cur < file.size) {
        chunks.push({ file: file.slice(cur, cur + size) })
        cur += size
    }
    return chunks
}

/**
 * @description: 获取文件的后缀名
 */
function getFileType(fileName) {
    return fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase()
}

export {
    calculateFileMd5ByDefaultChunkSize,
}
